<template>
    <div class="login">
        <div class="login-wrap"
            :style="{'background':`url(${staticImageUrl('/images/login/login_bg.png')}) no-repeat center center/cover`}">
            <div class="positionR displayFlex justifyCtBwt password-wlogin-text">
                <span class="iconfont icon-arrows_left" @click="goBack"></span>
                <span class="password-login" v-if="!resetPw"
                    @click="tapLoginWay">{{!passwordLogin?'密码登录':'验证码登录'}}</span>
                <span class="reset-login" v-else>重置密码</span>
                <span class="reset-login" v-if="!resetPw">{{passwordLogin?'密码登录':'验证码登录'}}</span>
            </div>
            <div class="login-phone-winput displayFlex flexCenter" :class="{'login-input-selcet':focusIndex==0}"
                @click="focusIndex=0">
                <img v-if="focusIndex==0" class="phone-icon" src="../../assets/images/login/phone_icon_blue.png" alt="">
                <img v-else class="phone-icon" src="../../assets/images/login/phone_icon_gray.png" alt="">
                <phone-check :porpsContent="phoneProps" @changeCheck="phoneCheckFn"></phone-check>
            </div>
            <div v-if="!passwordLogin || resetPw" class="login-code-winput displayFlex flexCenter"
                :class="{'login-input-selcet':focusIndex==1}" @click="focusIndex=1">
                <img v-if="focusIndex==1" class="verification-code"
                    src="../../assets/images/login/verification_code_light.png" alt="">
                <img v-else class="verification-code" src="../../assets/images/login/verification_code.png" alt="">
                <code-check ref="codeCheck" :codeMsgProps="codeProps" @getCode="getCode" @changeCheck="checkCodeFn">
                </code-check>
            </div>
            <div v-if="passwordLogin || resetPw" class="login-code-winput displayFlex flexCenter"
                :class="{'login-input-selcet':focusIndex==2}" @click="focusIndex=2">
                <img v-if="focusIndex==2" class="verification-code"
                    src="../../assets/images/login/password_icon_light.png" alt="">
                <img v-else class="verification-code" src="../../assets/images/login/password_icon.png" alt="">
                <div class="width-full displayFlex">
                    <check-password class="flex1" @checkPassword="checkPasswordFn" :propsContent="checkPassword">
                    </check-password>
                    <span class="displayFlex flexCenter eyes-wrap" @click="showPw">
                        <img v-if="!seePW" class="see-pws" src="../../assets/images/login/eye_close.png" alt="">
                        <img v-else class="see-pws" src="../../assets/images/login/eye_open.png" alt="">
                    </span>
                </div>
            </div>
            <div class="languege-code-wtext" v-if="!passwordLogin || resetPw">
                <span class="displayBlock voice-code-text1" v-if="!voice.showPhoneComing">收不到验证码？点击获取<span
                        class="languege-code-text" @click="getVoiceCode">语音验证码</span></span>
                <span class="displayBlock voice-code-text1" v-if="voice.showPhoneComing">电话快来了，请留意您的手机的来电</span>
            </div>
            <div class="displayFlex flexCenter">
                <button v-if="!resetPw" class="button" @click="toLogin" :class="{'disabled': !isCanSubmit}">登录</button>
                <button v-else class="button letter-space5" @click="submitEditPsw"
                    :class="{'disabled': !isCanSubmit}">完成并登录</button>
            </div>
            <div v-if="passwordLogin && !resetPw" class="padding20px positionR forget-password-wtext">
                <span class="forget-password" @click="resetPwFn">忘记密码?</span>
            </div>
        </div>
        <p class="login-treaty">
            注册登录即表示您知晓并同意 <router-link to="/userAgreement">《用户协议》</router-link>和 <router-link to="/privacy">《隐私政策》
            </router-link>。
        </p>
    </div>
</template>

<script>
import common from '../../assets/js/common/commonMethods'
import xtoken from '../../x/xtoken'
import { mapMutations,mapGetters } from 'vuex';

export default {
    name: "Login",
    data () {
        return {
            seePW: false,
            passwordLogin: true,
            resetPw: false,
            checkPassword: {},
            focusIndex: 0,
            isCanGetCode: false,
            isCanSubmit: false,
            longitude:0,
            latitude:0,
            hasThirdId: this.$store.state.currentUser && this.$store.state.currentUser.thirdId ? this.$store.state.currentUser.thirdId : null,
            phoneProps: {
                isShowRedWarn: false,
            },
            codeProps: {
                isShowRedWarn: false,
                isNeedClearIcon: false,
                codeLength: 4,
            },
            voice: {
                showPhoneComing: false,//codeCheck返回的参数
                voiceTimer: 0,//语音验证码定时器
                voiceTime: 0,//语音验证码时间
            },
            getCodeText: '获取验证码',
            getCodeTimer: '',
            phoneObj: { phoneTrue: false, phoneNum: '' },
            codeObj: { codeTrue: false, code: null },
            passwordObj: { passwordTrue: false, password: null },
        }
    },
    mounted () {
        let userLongitude= this.currentUser && Object.keys(this.currentUser).includes('longitude') ? this.currentUser.longitude :  0;
        let userLatitude= this.currentUser && Object.keys(this.currentUser).includes('latitude')  ? this.currentUser.latitude :  0;
        let thirdLongitude= this.currentThird && Object.keys(this.currentThird).includes('longitude')  ? this.currentThird.longitude :  0;
        let thirdLatitude= this.currentThird && Object.keys(this.currentThird).includes('latitude')  ? this.currentThird.latitude :  0;
        this.longitude = userLongitude ? userLongitude : thirdLongitude;
        this.latitude = userLatitude ? userLatitude : thirdLatitude;
    },
    computed:{
        ...mapGetters({
                currentUser: 'currentUserFn',
                currentThird: 'currentThirdFn',
            }
        ),
    },
    methods: {
        ...mapMutations(['discountRoom']),
        closeReset () {
            this.resetPw = false;
        },

        showPw () {
            let that = this;
            that.seePW = !that.seePW;
            let canSeeObj = { canSee: that.seePW };
            that.checkPassword = Object.assign({}, that.checkPassword, canSeeObj);
        },
        tapLoginWay () {
            this.passwordLogin = !this.passwordLogin;
            /*验证是否可以提交验证码*/
            setTimeout(() => {
                if (this.phoneObj.phoneTrue && this.$refs.codeCheck && this.$refs.codeCheck.codeMsg.codeDown == '获取验证码') {
                    this.codeProps.isCangetCode = true;
                    this.codeProps = Object.assign({}, this.codeProps);
                } else {
                    this.codeProps.isCangetCode = false;
                    this.codeProps = Object.assign({}, this.codeProps);
                }
            }, 100)
            this.checkIsCanSubmit();
        },
        /*在忘记密码页面的时候不后退只是回到密码登录的状态*/
        goBack () {
            let that = this;
            if (this.resetPw) {
                this.resetPw = false;
                document.title = "登录";
            } else {
                this.$router.go(-1);
                // common.goBack()
            }
        },
        resetPwFn () {
            document.title = "忘记密码";
            this.resetPw = true;
            let canSeeObj = { placeholder: '请输入6-20位新密码' };
            /*验证是否可以提交验证码*/
            setTimeout(() => {
                if (this.phoneObj.phoneTrue && this.$refs.codeCheck && this.$refs.codeCheck.codeMsg.codeDown == '获取验证码') {
                    this.codeProps.isCangetCode = true;
                    this.codeProps = Object.assign({}, this.codeProps);
                } else {
                    this.codeProps.isCangetCode = false;
                    this.codeProps = Object.assign({}, this.codeProps);
                }
            }, 50)
            this.checkPassword = Object.assign({}, this.checkPassword, canSeeObj);
            this.checkIsCanSubmit();
        },
        phoneCheckFn (obj) {
            if (!this.passwordLogin || this.resetPw) {
                if (obj.phoneTrue && this.$refs.codeCheck.codeMsg.codeDown == '获取验证码') {
                    this.codeProps.isCangetCode = true;
                    this.codeProps = Object.assign({}, this.codeProps);
                } else {
                    this.codeProps.isCangetCode = false;
                    this.codeProps = Object.assign({}, this.codeProps);
                }
            }
            this.phoneObj = Object.assign({}, this.phoneObj, obj);
            this.checkIsCanSubmit();
        },
        checkCodeFn (obj) {
            this.codeObj = Object.assign({}, this.codeObj, obj);
            this.checkIsCanSubmit();
        },
        checkPasswordFn (obj) {
            this.passwordObj = Object.assign({}, this.passwordObj, obj);
            this.checkIsCanSubmit();
        },
        // 获取语音验证码
        getVoiceCode () {
            if (!this.phoneObj.phoneNum) {
                this.$root.$emit('toast', { msg: '请输入手机号码' });
                return
            }
            this.$store.dispatch('sendVoiceCodeApi', this.phoneNum).then((data) => {
                if (data.success) {
                    this.voice.showPhoneComing = true;
                } else if (data.errMsg) {
                    this.$root.$emit('toast', { msg: data.errMsg })
                } else {
                    this.$root.$emit('toast', { msg: '语音验证码获取失败' });
                }
            })
            // let url = `${this.NW_API}/api/voice/code/send/phone/${this.phoneObj.phoneNum}?length=4`
            // if (this.voice.voiceTime == 0) {
            //     this.$root.$emit('toast', { msg: '请注意手机来电' });
            //     if (this.voice.voiceTimer) {
            //         clearInterval(this.voice.voiceTimer);
            //     }
            //     this.voice.voiceTime = 60;
            //     this.voice.voiceTimer = setInterval(() => {
            //         this.voice.voiceTime--;
            //         if (this.voice.voiceTime <= 0) {
            //             clearInterval(this.voice.voiceTimer);
            //         }
            //     }, 1000);
            //     this.xurl.put(url).then((data) => {
            //         if (data.success) {
            //             this.voice.showPhoneComing = true;
            //         } else if (data.errMsg) {
            //             this.$root.$emit('toast', { msg: data.errMsg })
            //         } else {
            //             this.$root.$emit('toast', { msg: '语音验证码获取失败' });
            //         }
            //     })
            // } else {
            //     this.$root.$emit('toast', { msg: '语音验证码60秒获取一次' });
            // }
        },
        /*获取验证码*/
        getCode () {
            let that = this;
            this.codeProps.isCangetCode = false;
            this.codeProps.time = 60;
            this.codeProps = Object.assign({}, this.codeProps);
            let url = `${this.NW_API}/api/send/code/phone/${this.phoneObj.phoneNum}`;
            this.xurl.post(url).then((result) => {
                that.$root.$emit('toast', { msg: '发送验证码成功' });
                that.getCodeTimer = setInterval(() => {
                    that.codeProps.time--;
                    that.codeProps.codeDown = `<span class="color-gray-disabled">${that.codeProps.time}s</span>`;
                    that.codeProps = Object.assign({}, that.codeProps);
                    if (that.codeProps.time < 0) {
                        that.codeProps.isCangetCode = true;
                        that.codeProps.codeDown = `重新获取`;
                        that.codeProps = Object.assign({}, this.codeProps);
                        clearInterval(that.getCodeTimer);
                    }
                }, 1000);
            }).catch(() => {
                that.codeProps.isCanGetCode = true;
                that.codeProps.codeDown = `获取验证码`;
                that.codeProps = Object.assign({}, this.codeProps);
            })
        },
        /*点击登录*/
        toLogin () {
            let url = '';
            let paramas = {};
            let that = this;

            if (this.passwordLogin) {
                url = `${this.NW_API_API_LOCALE_VERSION}/user/account/password/login`;
                paramas = {
                    "phone": that.phoneObj.phoneNum,
                    "password": that.passwordObj.password,
                    "thirdId": that.hasThirdId,                 //----微信授权登录绑定手机号码时才传 !!    ++20190805++
                    "deviceType": "H5",
                    "terminalType": "CustomerH5",
                    "deviceId": xtoken.getDeviceId(),
                    "longitude": this.longitude,                     //----经度                  ++20200615++
                    "latitude":  this.latitude                      //----纬度                  ++20200615++
                }
            } else {
                url = `${this.NW_API_API_LOCALE_VERSION}/user/account/code/login`;
                paramas = {
                    "phone": that.phoneObj.phoneNum,
                    "authCode": that.codeObj.code,
                    "thirdId": that.hasThirdId,                 //----微信授权登录绑定手机号码时才传 !!    ++20190805++
                    "deviceType": "H5",
                    "terminalType": "CustomerH5",
                    "deviceId": xtoken.getDeviceId(),
                    "longitude": this.longitude,                     //----经度                  ++20200615++
                    "latitude":  this.latitude                      //----纬度                  ++20200615++
                }
            }
            this.xurl.postDataJsonLoading(url, paramas).then((data) => {
                if (data.success) {
                    let nextPage = window.localStorage.getItem(this.NEXTPAGE) || '';
                    this.$store.dispatch('updateCurrentUser', data.result);
                    if (nextPage) {
                        window.location.href = nextPage;
                    } else {
                        this.$router.push({ path: '/home' })
                    }
                } else {
                    this.$root.$emit("toast", { msg: "登录失败，请重新登录" });
                }
            })
        },
        /*提交修改密码*/
        submitEditPsw () {
            let url = `${this.NW_API_API_LOCALE_VERSION}/user/account/forget/pwd/login`;
            let that = this;
            let paramas = {
                "phone": that.phoneObj.phoneNum,         //----手机号码    必传
                "authCode": that.codeObj.code,           //----验证码
                "newPwd": that.passwordObj.password,              //----新密码，明文
                "deviceType": "H5",            //----设备类型
                "terminalType": "CustomerH5",
                "deviceId": xtoken.getDeviceId(),           //----设备ID
                "longitude": this.longitude,                     //----经度                  ++20200615++
                "latitude":  this.latitude                      //----纬度                  ++20200615++
            };
            this.xurl.postDataJsonLoading(url, paramas).then((data) => {
                let nextPage = window.localStorage.getItem(this.NEXTPAGE);
                this.$store.dispatch('updateCurrentUser', data.result);
                if (nextPage) {
                    window.location.href = nextPage;
                } else {
                    this.$router.push({ path: '/home' })
                }
            })
        },
        checkIsCanSubmit () {
            let isResetPw = this.resetPw ? this.codeObj.codeTrue && this.passwordObj.passwordTrue : this.codeObj.codeTrue || this.passwordObj.passwordTrue
            if (this.phoneObj.phoneTrue && isResetPw) {
                this.isCanSubmit = true;
            } else {
                this.isCanSubmit = false;
            }
        },
    },
    components: {
        'phone-check': () => import("../../components/commonComponents/phone/PhoneCheck"),
        'code-check': () => import("../../components/commonComponents/codeCheck/CodeCheck"),
        'check-password': () => import("../../components/commonComponents/password/CheckPassword"),
    }
}
</script>

<style scoped lang="scss">
@import url($css_root+"css/login/login.css");
.login /deep/ {
    .phone-input,
    .code-input,
    .count-down-wrap,
    .password-input {
        border: none;
        height: 0.3rem;
        padding-left: 0.1rem;
        margin-top: 0;
        line-height: 0.2rem;
    }
    .booking_close_button {
        top: -0.04rem;
    }
    .count-down-wrap {
        height: auto;
    }
    .code-input-wrap {
        display: flex;
        align-items: center;
    }
    .languege-code-wtext {
        color: #999999;
        font-size: 0.12rem;
        margin: 0 auto;
        margin-top: 0.15rem;
        // width: 3rem;
        text-align: center;
        .languege-code-text {
            color: #5d89e8;
        }
    }
    .code-input,
    .count-down,
    .phone-input,
    .password-input {
        background-color: transparent;
    }
    .code-input,
    .phone-input.password-input {
        font-weight: bold;
    }
    .phone-input::-webkit-input-placeholder,
    .code-input::-webkit-input-placeholder,
    .password-input::-webkit-input-placeholder {
        font-size: 0.16rem;
        font-weight: normal;
    }
    .phone-input::placeholder,
    .code-input::placeholder,
    .password-input::placeholder {
        font-size: 0.16rem;
        font-weight: normal;
    }
    .count-down {
        font-size: 0.14rem;
        color: #5d89e8;
    }
    .disabled.count-down {
        color: #5d89e8;
        opacity: 0.5;
    }
    .phone-input {
        color: #333333;
    }
    .password-input {
        width: 100%;
    }
}
</style>